package lookas;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.imageio.ImageIO;
import javax.sql.DataSource;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

public class PlakatPreview extends JFrame{
    private static final long  serialVersionUID = -3879943885987516912L;
    private SimpleJdbcTemplate simpleJdbcTemplate;

    public void setDataSource(DataSource dataSource){
        simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
    }

    public PlakatPreview(){}

    public void preview(final String link){
        simpleJdbcTemplate.getJdbcOperations().execute(
            new ConnectionCallback(){
                public Object doInConnection(Connection con)
                    throws SQLException, DataAccessException{

                    PreparedStatement st = con
                        .prepareStatement("SELECT f.tytul T, f.plakat P FROM film f where f.link = ?");

                    st.setString(1, link);

                    ResultSet rs = st.executeQuery();
                    int i = 0;
                    if(rs.next()){
                        i++;
                        String tytul = rs.getString("T");
                        Blob blob = rs.getBlob("P");
                        if(blob == null)
                            return null;
                        BufferedInputStream imageStream = new BufferedInputStream(
                            blob.getBinaryStream());
                        BufferedImage image = null;
                        try{
                            image = ImageIO.read(imageStream);
                            imageStream.close();
                            ImageIcon icon = new ImageIcon(image);
                            JLabel iLabel = new JLabel(icon);
                            getContentPane().removeAll();
                            getContentPane().add(iLabel);
                            setSize(icon.getIconWidth() + 10, icon
                                .getIconHeight() + 40);
                            setTitle(tytul);
                            setVisible(true);
                        }catch(IOException e){}
                    }
                    return null;
                }
            });
    }
}
